<template>
  <div class="register">
    <!-- 上传头像 -->
    <div class="userphoto">
     <van-uploader :after-read="afterRead" :show-upload="isflag" class="imgload"/>
    <img :src="imgUrl" v-if="imgUrl" class="img" alt="" /> 
    </div>
    <!-- 填写个人信息 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="userName"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="nickname"
        name="nickName"
        label="昵称"
        placeholder="昵称"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <!-- 点击注册 -->
      <div class="clickBtn">
        <van-button size="small" square block type="info" native-type="submit" class="btn"
          >注册</van-button
        >

        <van-button size="small" plain hairline type="info" class="btn" @click="onClick">去登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { reqRegisterAPI } from "../api/user";
import { Toast } from "vant";
export default {
  data() {
    return {
      username: "", 
      password: "", 
      nickname: "", 
      imgUrl: "", 
      isflag:true,
    };
  },
  computed: {},
  watch: {
    // 监听是否上传图片
    imgUrl(pic){
      if(pic){
        this.isflag=false
      }

    }
    
  },

  methods: {
    onClick(){
      this.$router.push("/login");
    },

    async onSubmit(values) {
      console.log("submit", values);
      const result = await reqRegisterAPI({ ...values, avatar: this.imgUrl });
      console.log(result);
      if (result.code === "success") {
        Toast("注册成功");
        this.$router.push("/login");
      }
    },
    afterRead(file) {
      //将文件上传至服务器 
      this.imgUrl = file.content;
    },
  },
  created() {},
  mounted() {},
  components: {},
};
</script>
<style scoped lang="less">
.register {
  .img {
    width: 80px;
    height: 80px;
  }

  .userphoto{
    text-align: center;
  }

  .clickBtn{
    width: 160px;
    margin: 0 auto;
    // margin-top: 30px;
  }

  .btn{
    width: 160px;
    font-size: 15px;
    margin-top: 30px;
    
  }
}
</style>
